package org.shark.colortheme.fragment;

import org.shark.colortheme.ColorThemeApplication;
import org.shark.colortheme.R;
import org.shark.colortheme.adapter.ThemeAdapter;
import org.shark.colortheme.core.ColorThemeManager;
import org.shark.colortheme.core.PackageThemeObserver;
import org.shark.colortheme.core.ThemePackage;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.GridView;

public class ThemeLoaderFragment extends Fragment implements PackageThemeObserver,OnItemClickListener{
	View rootView;
	GridView mGridView;
	ThemeAdapter mThemeAdapter;
	public static ThemeLoaderFragment newInstance() {
		ThemeLoaderFragment fragment = new ThemeLoaderFragment();
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.root_ft_themeloader, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		rootView = getView();
		mGridView = (GridView) rootView.findViewById(R.id.grid_theme);
		ColorThemeManager.getInstance().addStyleObserver(this);
		mThemeAdapter = new ThemeAdapter(getActivity(), ColorThemeManager.getInstance().getThemePackages());
		mGridView.setAdapter(mThemeAdapter);
		mGridView.setOnItemClickListener(this);
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ThemePackage _item = mThemeAdapter.getItem(position);
		if(_item!=null){
			ColorThemeApplication.getInstance().setActivityBackground(_item.getActivityBackground());
		}
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		ColorThemeManager.getInstance().deleteStyleObserver(this);
	}
	
	@Override
	public void onInstallPackageTheme(ThemePackage theme) {
		mThemeAdapter.add(theme);
		mThemeAdapter.notifyDataSetChanged();
	}
	
	@Override
	public void onUnInstallPackageTheme(ThemePackage theme) {
		mThemeAdapter.remove(theme);
		mThemeAdapter.notifyDataSetChanged();
	}

}
